package com.splant.android.smart.SystemDefinedLevel.UserAddress;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by Administrator on 2015/9/29.
 */
public class UserAddress {
    //获取客户IP和所在城市
    public static String getAddressJson()
    {
        String objStr="";
        InputStream ins = null;
        try
        {
            URL url = new URL("http://pv.sohu.com/cityjson");
            URLConnection con = url.openConnection();
            ins = con.getInputStream();
            InputStreamReader isReader = new InputStreamReader(ins, "GB2312");
            BufferedReader bReader = new BufferedReader(isReader);
            StringBuffer webContent = new StringBuffer();
            String str = null;
            while ((str = bReader.readLine()) != null) {
                webContent.append(str);
            }
            objStr=webContent.toString();


        } catch (Exception e) {

        }
        finally
        {
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return objStr;
        }
    }

    //获取外网IP
    public static String getWanIP()
    {
        String  ipStr="";
        try
        {
            String objStr=getAddressJson();
            objStr=objStr.substring(19,objStr.length()-1);
            JSONObject obj=new JSONObject(objStr);
            ipStr=obj.getString("cip");
        }
        catch (Exception e)
        {

        }
        return ipStr;
    }
    public static String getUserCity()
    {
        String  cityName="";
        try
        {
            String objStr=getAddressJson();
            objStr=objStr.substring(19,objStr.length()-1);
            JSONObject obj=new JSONObject(objStr);
            cityName=obj.getString("cname");
            int startIndex=cityName.indexOf("省")+1;
            int endIndex=cityName.length()-1;
            cityName=cityName.substring(startIndex,endIndex);
        }
        catch (Exception e)
        {

        }
        return cityName;
    }
}
